package poli.tidia.mobile.proxy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import poli.tidia.mobile.model.Folder;
import poli.tidia.mobile.model.Resource;
import poli.tidia.mobile.model.Site;

public class ResourcesProxy {
	public List<Resource> getResources(Site site, Folder folder)
	{
		List<Resource> result = new ArrayList<Resource>();
		
        try {
        	Document doc;
        	String response;
        	RestClient client;
        	if(site.getResourcesPortletUrl().equals(""))
        	{
	        	client = RestClient.getInstance(site.getResourcesUrl());
	            client.Execute(RestClient.RequestMethod.GET);
				response = client.getResponse();
		        doc = Jsoup.parse(response);
		        site.setResourcesPortletUrl(doc.select(".portletMainWrap").first().child(0).attr("src"));
        	}
        	
        	client = RestClient.getInstance(site.getResourcesPortletUrl());
        	if (folder != null)
        	{
        		client.AddParam("collectionId", folder.getAddress());
        		client.AddParam("sakai_action", "doNavigate");
        	}

        	client.Execute(RestClient.RequestMethod.POST);
        	response = client.getResponse();
        	doc = Jsoup.parse(response);
        	Elements resourcesDOM = doc.select("table").select("tr[class]:gt(1)");
        	for (int i = 0; i < resourcesDOM.size(); i++) {
				String name = resourcesDOM.get(i).select("td[headers=title]").select("a").last().text().trim();
				String strDate = resourcesDOM.get(i).select("td[headers=modified]").text().trim().split(" ")[0];
				SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
	        	Date modifiedDate = curFormater.parse(strDate); 
	        	Boolean isFolder = resourcesDOM.get(i).select("td[headers=size]").text().endsWith(" itens");
        		
	        	if(isFolder)
	        	{
					String unparsedAddress = resourcesDOM.get(i).select("td[headers=title]").select("a").first().attr("onclick");
					unparsedAddress = unparsedAddress.substring(unparsedAddress.indexOf("document.getElementById('collectionId').value='") + 47);
	        		String address = unparsedAddress.substring(0, unparsedAddress.indexOf("'"));
	        		
	        		int childCount = Integer.parseInt(resourcesDOM.get(i).select("td[headers=size]").text().split(" ")[0]);
	        		result.add(new Folder(address, modifiedDate, name, childCount));
	        	}
	        	else
	        	{
	        		String address = resourcesDOM.get(i).select("td[headers=title]").select("a").first().attr("href");
	        		result.add(new Resource(address, modifiedDate, name));	
	        	}
			}
        } catch (Exception e) {
            e.printStackTrace();
        }

		return result;
	}
}
